<template>
  <div class="app-container" style="padding:0px;" v-cloak>
    <div style="height: 550px;display: flex;align-items: flex-start;">
      <div class="l" style="margin-right: 10px;width: 350px;height: 550px;overflow-y: scroll;">
        <el-card shadow="never" class="cardBg" style="width: 330px">
          <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane label="单规格设置" name="first">
            </el-tab-pane>
            <el-tab-pane label="多规格设置" name="second">
              <el-form ref="attrForm" label-position="top" label-width="300px">
                <div class="stepThird" style="width:100%">
                  <el-button type="primary" icon="el-icon-circle-plus" class="addSpecificaType" @click="_addSpecifoca">添加规格类型</el-button>
                  <div v-for="(item,index) in templateAttrData" :key="`item${index}`" class="itemTag">
                    <div class="outerBorder">
                      <div class="close" @click="_deleteTemplateAttrData(index)">
                        <i class="el-icon-error" />
                      </div>
                      <div class="inputMar">
                        <el-select v-model="item.name" placeholder="请选择规格" @change="onChangeProgram" @focus="onFocusProgram(index)">
                          <el-option
                            v-for="item in attrKeyList"
                            :key="item.id"
                            :disabled="item.disable"
                            :label="item.attrName"
                            :value="item.attrName"/>
                        </el-select>
                      </div>
                      <div v-show="item.name">
                        <el-tag v-for="tag in item.dynamicTags" :key="`${tag}index`" closable :disable-transitions="false" @close="handleClose(tag, item)">{{ tag }}</el-tag>
                        <el-input v-if="item.tagInputVisible" :ref="'saveTagInput'+index" v-model="item.tagInputValue" v-focus="item.focusState" class="input-new-tag" size="small" @keyup.enter.native="handleInputConfirm(item, index)" @blur="handleInputConfirm(item, index)" />
                        <el-button v-else class="button-new-tag" size="small" @click="_addshowInput(item, index)">+ {{ item.name }}</el-button>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="rigEnd">
                  <el-button type="primary" class="saveBtn" @click="_nextStep">生成规格列表</el-button>
                </div>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>

      <div class="r" style="height: 550px;overflow-y: scroll;">
        <el-card shadow="never" class="cardBg" style="padding-top:0px">
          <el-table :data="skuList" v-loading="listLoading" style="width: 100%;margin-top: 0px" border >
            <el-table-column label="SKU编码" width="150" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuCode" oninput="value=value.replace(/[^\d]/g,'')" disabled/>
              </template>
            </el-table-column>
            <!-- 销售属性列动态显示 -->
            <el-table-column v-for="(item,index) in templateNameList" :key="item.id" :label="templateNameList[index]" width="100" align="center">
              <template slot-scope="scope">
                {{ getProductSkuSp(scope.row,index) }}
              </template>
            </el-table-column>
            <el-table-column label="原价" width="100" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuCostprice" onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" />
              </template>
            </el-table-column>
            <el-table-column label="现价" width="100" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuStock" onkeyup="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''" />
              </template>
            </el-table-column>
            <el-table-column label="库存" width="90" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuSaleprice" oninput="value=value.replace(/[^\d]/g,'')" />
              </template>
            </el-table-column>
            <el-table-column label="图片" width="110" align="center" v-if="activeName==='second'">
              <template slot-scope="scope">
                <el-upload
                  :action="CMBASE.baseUploadAction"
                  :file-list="scope.row.fileList"
                  :show-file-list="false"
                  :on-preview="handlePreview"
                  :on-remove="(value,fileList)=> handRemoveColumn(scope.$index, value,fileList)"
                  :on-success="(value)=> handleAvatarSuccessColumn(scope.$index,value)"
                  class="upload-demo  avatar-uploader "
                  list-type="picture">
                  <img v-if="scope.row.skuImgurl" :src="scope.row.skuImgurl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column v-if="showDeleteColumn" label="操作" width="60" align="center" >
              <template slot-scope="scope">
                <el-button type="text" @click="handleRemoveProductSku(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>

import { getMAttrKeyListByparams, getMAttrValueListByParams, saveGoodsSkuInfo, getGoodsSkuInfo } from '@/api/modules/goodsInfo'

export default {
  name: 'GoodsAttrForm',
  components: {},
  directives: {
    focus: {
      // 根据focusState的状态改变是否聚焦focus
      update: function(el, value) {
        // 第二个参数传进来的是个json
        if (value) {
          el.focus()
        }
      }
    }},
  filters: {},
  props: {
    // 商品ID
    rowGoodsId: {
      type: String,
      required: true
    },
    // 商品分类ID
    rowClassifyId: {
      type: String,
      required: true
    },
    // 商品规格字符串
    rowSkuAttr: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      listLoading: true,
      showDeleteColumn: false,
      selectProductAttr: [],
      attrValueList: [],
      columnCheck: [],
      skuList: [],

      resSkuList: [], // 商品已保存规格值 多规格
      resSingleSkuList: [], // 商品已保存规格值 单规格
      resSkuNameList: [], // 后台已保存规格名称

      templateAttrData: [], // 每一个sku规格的数据
      dynamicTags: [], // 每一个sku规格里面拟定的数据如：颜色里面的[红色，蓝色，黄色]这些
      templateNameList: [], // 这个是第四步步骤里的for循环的颜色的模板名称，如[颜色，尺寸，库存，价格]
      attrKeyList: [],
      currentSelect: -1, // 当前选中的select框的 index
      activeName: 'first'
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    // 初始化表单数据
    initFormData() {
      this.listLoading = true
      // 根据分类Id获取商品规格
      this.getAttrKeyListByGoodsId(this.rowClassifyId, this.rowGoodsId) // 属性多选框渲染
      // 根据商品Id获取SKU列表
      this.getSkuListByGoodsId(this.rowGoodsId)
      this.selectProductAttr = this.rowSkuAttr === null || this.rowSkuAttr === '' ? null : JSON.parse(this.rowSkuAttr)
    },

    // 根据商品id 获取销售属性列表
    getAttrKeyListByGoodsId(classify, goodsId) {
      // 【API请求】----获取销售属性列表
      getMAttrKeyListByparams({ classify: classify, goodsId: goodsId }).then(response => {
        console.log(response)
        this.attrKeyList = response.result
      })
    },

    // 根据商品id获取 SKU列表
    getSkuListByGoodsId(goodsId) {
      // 获取sku信息
      getGoodsSkuInfo({ goodsId: goodsId }).then(response => {
        const resDate = response.result
        // 商品未设置规格信息
        if (resDate == null || resDate.length === 0) {
          this.listLoading = false
          this.setSkuList()
          return
        }
        // 判断是否为单规格商品
        if (resDate.length === 1 && (resDate[0].attrInfo == null || resDate[0].attrInfo.length === 0)) {
          const item = resDate[0]
          // 列表图片信息
          item.fileList = []
          if (item.skuImgurl != null && item.skuImgurl !== '') {
            const photoArray = []
            if (item !== '') {
              photoArray.push({ url: '' + item })
            }
            item.fileList = photoArray
          }
          this.skuList.push(item)
          this.resSingleSkuList = this.skuList
          this.listLoading = false
          return
        } else {
          // 判断商品如果为多规格
          this.activeName = 'second'
          // 规格属性表头列表
          const attrInfoData = JSON.parse(resDate[0].attrInfo)
          attrInfoData.forEach(item => {
            this.resSkuNameList.push(item.name)
          })
          this.templateNameList = this.resSkuNameList
          // value列表
          resDate.forEach(item => {
            const attrInfoArray = JSON.parse(item.attrInfo)
            item.attrInfo = attrInfoArray // 列表SKU信息
            // 列表图片信息
            item.fileList = []
            if (item.skuImgurl != null && item.skuImgurl !== '') {
              const photoArray = []
              if (item !== '') {
                photoArray.push({ url: '' + item })
              }
              item.fileList = photoArray
            }
          })
          this.resSkuList = resDate
          this.skuList = resDate
          this.listLoading = false
        }
      }).catch(() => {
        this.listLoading = false
        this.$message({ message: '商品SKU列表获取失败', type: 'error' })
      })
    },

    // 单规格设置skuList
    setSkuList() {
      this.skuList = []
      this.templateNameList = []
      // 渲染SKU列表
      this.skuList.push({
        skuPrice: '0',
        skuCostprice: '0',
        skuSaleprice: '0',
        skuStock: '0',
        skuImgurl: '',
        skuCode: Date.parse(new Date()).toString().substr(0, 10) + '-' + Math.floor(Math.random() * 900) + 100
      })
    },

    // 添加规格类型
    _addSpecifoca() {
      this.templateAttrData.push({
        name: '',
        dynamicTags: [],
        tagInputVisible: false,
        tagInputValue: '',
        focusState: false,
        selectedId: ''
      })
    },

    // 删除商品规格
    _deleteTemplateAttrData(index) {
      debugger
      const attrKeyListIndex = this.attrKeyList.findIndex(item => item.id === this.templateAttrData[index].selectedId)
      if (attrKeyListIndex >= 0) this.attrKeyList[attrKeyListIndex].disable = false
      this.$forceUpdate()
      this.templateAttrData.splice(index, 1)
    },

    // 删除单个标签
    handleClose(tag, item) {
      item.dynamicTags.splice(item.dynamicTags.indexOf(tag), 1)
    },

    // 按下enter或者失去焦点的时候触发Input里面的值到<el-tag>
    handleInputConfirm(item, index) {
      const tagInputValue = item.tagInputValue
      if (tagInputValue) {
        if (item.dynamicTags.indexOf(tagInputValue) === -1) {
          item.dynamicTags.push(tagInputValue)
        } else {
          // Message.warning('请勿重复输入')
        }
      }
      item.tagInputVisible = false
      item.tagInputValue = ''
    },

    // 点击变成输入框
    _addshowInput(item, index) {
      item.tagInputVisible = true
      this.$nextTick(() => {
        item.focusState = true
      })
    },

    // 下一步步骤
    _nextStep() {
      this.showDeleteColumn = true
      const array = []
      this.$confirm('生成规格列表将删除之前的规格数据，是否要生成', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.templateNameList = []
        this.selectProductAttr = []
        this.templateAttrData.forEach(element => {
          this.templateNameList.push(element.name)
          this.columnCheck.push({ id: element.selectedId, attrName: element.name })
          array.push(element.dynamicTags)
          this.selectProductAttr.push({ id: element.selectedId, attrName: element.name, itemList: element.dynamicTags, values: element.dynamicTags })
        })
        // 刷新之前先清空sku列表
        this.skuList = []
        // 生成SKU列表
        this.getSkuData([], 0, array)
        console.log('skulist:', this.skuList)
        console.log('selectProductAttr:', this.selectProductAttr)
      }).catch(() => {
        // this.$message.error('sku组合失败')
      })
    },

    // select 当input获得焦点时触发
    onFocusProgram(index) {
      this.currentSelect = index
    },

    // select 选中值发生变化时触发
    onChangeProgram(value) {
      const attrKeyListIndex = this.attrKeyList.findIndex(item => item.id === this.templateAttrData[this.currentSelect].selectedId)
      if (attrKeyListIndex >= 0) this.attrKeyList[attrKeyListIndex].disable = false
      const index = this.attrKeyList.findIndex(item => item.attrName === value) // 到当前选中的找
      this.templateAttrData[this.currentSelect].selectedId = this.attrKeyList[index].id
      this.attrKeyList[index].disable = true
      this.templateAttrData[this.currentSelect].dynamicTags = []
      this.getAttrValueListByKeyId(this.attrKeyList[index].id)
      this.$forceUpdate()
    },

    // 根据规格键值key 获取规格值列表
    async getAttrValueListByKeyId(keyId,) {
      // 【API请求】----获取销售属性值列表
      await getMAttrValueListByParams({ keyIds: keyId }).then(response => {
        this.attrValueList = response.result.content
        this.attrValueList.find(item => {
          this.templateAttrData[this.currentSelect].dynamicTags.push(item.value)
        })
      })
    },

    // 销售属性列渲染
    getProductSkuSp(row, index) {
      console.log(row)
      const valueName = row.attrInfo[index].value
      return valueName
    },

    // 生成SKU信息
    getSkuData(skuArr = [], i, list) {
      for (let j = 0; j < list[i].length; j++) {
        const name = this.selectProductAttr[i].attrName
        if (i < list.length - 1) {
          skuArr[i] = { name: name, value: list[i][j] }
          this.getSkuData(skuArr, i + 1, list) // 递归循环
        } else {
          const temp = { name: name, value: list[i][j] }
          var tmp = Date.parse(new Date()).toString().substr(0, 10)
          var rand = Math.floor(Math.random() * 900) + 100
          // 渲染SKU列表
          this.skuList.push({
            attrInfo: [...skuArr, temp],
            skuPrice: '0',
            skuCostprice: '0',
            skuSaleprice: '0',
            skuStock: '0',
            skuImgurl: '',
            skuCode: tmp + '-' + rand
          })
        }
      }
    },

    // 移除某一行SKU 信息
    handleRemoveProductSku(index, row) {
      const list = this.skuList
      if (list.length === 1) {
        list.pop()
      } else {
        list.splice(index, 1)
      }
    },

    // 保存sku 表单
    async saveSkuFrom() {
      if (this.skuList.length === 0) {
        this.$message({ message: '请填写sku信息', type: 'error' })
        return
      }
      for (let i = 0; i < this.skuList.length; i++) {
        if (this.skuList[i].skuSaleprice <= 0 || this.skuList[i].skuCostprice <= 0) {
          this.$message({ message: '价格不能小于0', type: 'error' })
          return
        }
        if (parseFloat(this.skuList[i].skuCostprice) < parseFloat(this.skuList[i].skuSaleprice)) {
          this.$message({ message: '原价不能小于现价', type: 'error' })
          return
        }
      }
      const skuInfoArray = []
      this.skuList.forEach(item => {
        skuInfoArray.push({
          id: item.id,
          goodsId: this.rowGoodsId,
          attrInfo: item.attrInfo, // 属性json信息
          skuPrice: item.skuPrice,
          skuCostprice: item.skuCostprice,
          skuSaleprice: item.skuSaleprice,
          skuStock: item.skuStock,
          skuImgurl: item.skuImgurl,
          skuCode: item.skuCode
        })
      })
      const skuInfoArrayStr = JSON.stringify(skuInfoArray)
      console.log('save方法', this.selectProductAttr)
      const spuAttrInfo = this.selectProductAttr != null && this.selectProductAttr.length > 0 ? JSON.stringify(this.selectProductAttr) : null
      const res = await saveGoodsSkuInfo({ skuInfoArray: skuInfoArrayStr, spuAttrInfo: spuAttrInfo, goodsId: this.rowGoodsId })
      if (res.code === 0) {
        this.$emit('attrformcallback') // 只能用小写
      }
    },

    // 图片上传成功后回显
    handleAvatarSuccessColumn(index, res) {
      this.skuList[index].skuImgurl = res.path
    },

    // 上传之前校验
    handlePreview(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/psd' || file.type === 'image/pdd'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传图片只能是jpeg/png/psd/pdd/ 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 移除一张图片
    handRemoveColumn(index, res, fileList) {
      if (fileList.length > 0) {
        const fileListArray = []
        fileList.forEach(item => {
          const start = this.CMBASE.baseFileContext.length
          const end = item.url.length
          const photoUrl = item.url.substring(start, end)
          fileListArray.push(photoUrl)
        })
        this.skuList[index].skuImgurl = fileListArray.join('__')
      } else {
        this.skuList[index].skuImgurl = ''
      }
    },

    // 选项卡跳转
    handleClick(tab, event) {
      const index = tab.index
      if (index === '0') {
        if (this.resSingleSkuList.length > 0) {
          this.skuList = this.resSingleSkuList
          this.templateNameList = []
        } else {
          this.setSkuList()
        }
      } else {
        this.skuList = this.resSkuList
        this.skuNameList = this.resSkuNameList
      }
    },
  }
}

</script>
<style scoped lang="scss">
  .stepThird{
    .addSpecificaType{
      margin-bottom: 10px;
    }
    .itemTag{
      margin-bottom: 20px;
      .outerBorder{
        width: 100%;
        border: 1px solid #eee;
        border-radius: 5px;
        padding: 10px;
        box-sizing: border-box;
        position: relative;
        .close{
          position: absolute;
          right: 0;
          top: 0;
          i{
            font-size: 20px;
            cursor: pointer;
          }
        }
        .inputMar{
          margin-bottom: 10px;
        }
      }
    }
  }
  .stepFour{
    width: 100%;
    margin: auto;
    &__name{
      width: 100%;
      box-sizing: border-box;
      border: 1px solid #eee;
      display: flex;
      align-items: center;
      .item{
        flex: 1;
        width: 120px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        font-size: 14px;
        border-right: 1px solid #eee;
        padding: 0 10px;
        box-sizing: border-box;
      }
    }
    &__box{
      &__panel{
        width: 100%;
        box-sizing: border-box;
        border: 1px solid #eee;
        display: flex;
        align-items: center;
        .item{
          flex: 1;
          width: 120px;
          height: 50px;
          line-height: 50px;
          text-align: center;
          font-size: 14px;
          border-right: 1px solid #eee;
          padding: 0 10px;
          box-sizing: border-box;
        }
      }
    }
  }
  .rigEnd {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
    /*.previousBtn{
      color: #333;
      margin-right: 20px;
    }*/
    .saveBtn{
      width: 100px;
      height: 36px;
    }
  }
</style>
<style scoped>
  [v-cloak] {
    display: none;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }
  .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

</style>
